package com.hrbxlh.actionImpl;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.hrbxlh.dao.*;
import com.hrbxlh.util.SessionValues;
import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hrbxlh.util.PubMethods;
import com.hrbxlh.util.pageUtil;
import org.springframework.transaction.interceptor.TransactionAspectSupport;


@Component("sourceActionImpl")
@Transactional
public class SourceActionImpl {
	
	@Resource(name="sourceDao")
	private SourceDao sourceDao;
	
	@Resource(name = "professionDao")
	private ProfessionDao professionDao;
	
	@Resource(name = "classDao")
	private ClassDao classDao;
	
	@Resource(name="courseDao")
	private CourseDao courseDao;
	
	@Resource(name = "relStuClassDao")
	private RelStuClassDao relStuClassDao;
	
	@Resource(name="homeworkTestDao")
	private HomeworkTestDao homeworkTestDao;
	
	@Resource(name="myCourseDao")
	private MyCourseDao myCourseDao;
	
	@Autowired
	@Qualifier("relationActionImpl")
	private RelationActionImpl relationActionImpl;
	
	@Resource(name="questionDao")
	private QuestionDao questionDao;

	@Resource(name = "memberDao")
	private MemberDao memberDao;

	//日志信息
	Logger logger = Logger.getLogger(SourceActionImpl.class.getName());

	/*
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  学生成绩列表页面。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	public Map<String, Object> getAllSourceList(Map<String, Object> paramMap,HttpSession session,HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			
			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId")) ;
			paramMap.put("stuorteaId", stuorteaId);
			List<Map<String, Object>> memberList = new ArrayList<>();
			//通过教师号获取此教师所属班级
			List<Map<String,Object>> classList = relStuClassDao.getClassAndCourseByStuorteaId(paramMap);
			List<String> returnClassList = relStuClassDao.getClassByStuorteaId(paramMap);
			if(classList!=null&&classList.size()!=0){
				paramMap.put("classList", classList);
				//通过教师号获取此教师所属课程
				List<Map<String,Object>> courseList = courseDao.getTeaTeachCourse(paramMap);
				if(courseList!=null&&courseList.size()!=0){
					paramMap.put("courseList", courseList);
					returnMap.put("courseList", courseList);
					for(int i=0;i<classList.size();i++){
						paramMap.put("listClassId",classList.get(i).get("classId"));
						paramMap.put("listCourseId",classList.get(i).get("courseId"));
						List<Map<String, Object>> tempList = sourceDao.getAllSourceList(paramMap);
						memberList.addAll(tempList);
					}
					returnMap.put("pageNow", pageNow);
					returnMap.put("classList", returnClassList);
					int page = pageNow;//相当于pageNo
					int count = pageSize;//相当于pageSize
					int size = memberList.size();
					int pageCount=size/count;
					int fromIndex = 0;
					if(page!=0){
						fromIndex = count * (page - 1);
					}else{
						fromIndex = pageCount;
					}

					int toIndex = fromIndex + count;
					if (toIndex >= size) {
						toIndex = size;
					}
					if(page>pageCount+1){
						fromIndex=0;
						toIndex=0;
					}
					returnMap.put("memberList", memberList.subList(fromIndex, toIndex));

					/*System.out.println(list.subList(fromIndex, toIndex));
					if(memberList.size()>=10){
						int num = (pageNow-1)*10+1;

					}else{
						returnMap.put("memberList", memberList);
					}*/

					//获取全部页数
				/*	paramMap.put("pageNow", 0);
					List<Map<String, Object>> allMemberList = sourceDao.getAllSourceList(paramMap);*/
					int totalPage = pageUtil.getTotalPage(memberList, pageSize);
					returnMap.put("totalPage", totalPage);
					returnMap.put("excelMemberList",memberList);
					logger.info("最后的map"+paramMap);
					//当前教师未结课班级下学生列表（如果放在成绩设置那，当改变权重时想要改变学生成绩时若当前成绩表中没有当前教师所教学生的成绩，则会报错）
					/*if(memberList.size()!=0){
						paramMap.put("memberList",memberList);
						//未结课的学生成绩列表
						List<Map<String, Object>> stuList = sourceDao.getNoEndCourseAllSourceList(paramMap);
						//20171020号 成绩设置又改为当当前登陆人更改成绩设置的时候将当前登陆人选择的课程下未结课的班级下的学生成绩做相应更改，结课的班级学生成绩不变(给我传courseId)
						for(int i=0;i<stuList.size();i++){
							Map<String,Object> stuMap = new HashMap<String,Object>();
							stuMap.put("stuorteaId",stuList.get(i).get("stuorteaId"));
							stuMap.put("courseId",stuList.get(i).get("courseId"));
							stuMap.put("classId",stuList.get(i).get("classId"));
							Map<String, Object> detailMap = sourceDao.getExamBySidAndCourseId(stuMap);
							//平时成绩换算值(参数是班号、课程号、学生平时分)
							BigDecimal finPromaceSource = this.proSource(stuMap, detailMap,session);
							//考试成绩换算值（参数考试成绩）
							BigDecimal examSource = this.examSource(stuMap, detailMap,session);
							//学生最后的成绩
							BigDecimal finSumSource = finPromaceSource.add(examSource);
							stuMap.put("sumSource", finSumSource);
							stuMap.put("finPromaceSource", finPromaceSource);
							stuMap.put("finExamSource", examSource);
							//编辑成绩表，将学生总成绩、平时成绩换算值、考试成绩换算值插入数据库。
							stuMap.put("type", 1);
							stuMap.put("stuorteaId",stuList.get(i).get("stuorteaId"));
							boolean flag = questionDao.saveQuestionByStuId(stuMap);
							if(flag){
								System.out.println("更新成绩成功");
							}
						}
					}
					List<Map<String, Object>> finMmemberList = sourceDao.getAllSourceList(paramMap);
					returnMap.put("memberList", finMmemberList);*/
				}else{
					returnMap.put("memberList", null);
					returnMap.put("pageNow", 1);
					returnMap.put("totalPage", 0);
					returnMap.put("classList", null);
				}
				
			}else{
				returnMap.put("memberList", null);
				returnMap.put("pageNow", 1);
				returnMap.put("totalPage", 0);
				returnMap.put("classList", null);
			}
			//通过教师号获取此教师所属课程
//			List<Map<String,Object>> courseList = courseDao.getTeaTeachCourse(paramMap);
//			returnMap.put("courseList", courseList);
			
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/*
	 * @param classId
	 * @return  通过班级id获取某班级下所属课程
	 * @throws IOException
	 */
	public Map<String, Object> getAllCourseListByClassId(Map<String, Object> paramMap,HttpSession session,HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId")) ;
			paramMap.put("stuorteaId", stuorteaId);
			//通过教师号和班级id获取此教师所属课程
			List<Map<String,Object>> courseList = courseDao.getAllCourseListByClassId(paramMap);
			returnMap.put("courseList", courseList);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * 导入成绩
	 * 评分规则：
	 * 1、查询这个人，这个班级下的平时成绩最高分数
	 2、x = 100/最高分，保留两位小数
	 3、y = 本学生的平时分 *  x
	 4、平时分总分数 =  y * 平时分的权重
	 5、考试成绩总分数 = 本学生的考试成绩 *（1-权重）
	 6、总成绩 = 平时成绩总分数 + 考试成绩总分数
	 * @param file
	 * @param session
	 * @param request
	 * @return
	 * @throws Exception
	 */
		 public Map<String,Object> imStuSoruce(String file, HttpSession session, HttpServletRequest request) throws Exception{

	       boolean flag1 =false;
	       Map<String,Object> paramMap = new HashMap<String,Object>();
	       Map<String,Object> returnMap = new HashMap<String,Object>();
	       //获取当前登陆人的工号
			 Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			 String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			paramMap.put("stuorteaId", stuorteaId);
			 //得到表格中所有的数据
			 Map<String,Object> excelMap = this.getAllByExcel(file,stuorteaId);
			 List<Map<String, Object>> listExcel= (List<Map<String, Object>>) excelMap.get("list");
	       if(listExcel!=null){
			   //查询成绩表是否有数据
			   List<Map<String, Object>> sourceList = sourceDao.getExam();
			   //通过学号删除学生原来的成绩信息，重新插入更新
			   sourceDao.delSoruceBystuorteaId(listExcel);
			   //先将考试成绩和平时成绩插入exam表中
			   flag1 = sourceDao.addSource(listExcel);
			   if(flag1){
				   for (int i=0;i<listExcel.size();i++) {
					   //从成绩表中查询成绩权重
					   //查询每个班级分数最高人的分数
					   List<Map<String, Object>> memList = sourceDao.getMaxPreforSource(listExcel.get(i));
					   logger.info("#########"+listExcel.get(i)+"查询每个班级分数最高人的分数"+memList);
					   //查询课堂权重。
					   paramMap.put("courseId",listExcel.get(i).get("courseId"));
					   Map<String,Object> sorceMap = sourceDao.getProWedith(paramMap);
					   if(sorceMap==null||sorceMap.size()==0){
						   returnMap.put("flag",false);
						   returnMap.put("msg","请设置权重");
						   //手动进行事务回滚
						   TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						   return returnMap;
					   }
					   BigDecimal wedith = (BigDecimal) sorceMap.get("classPerformance");
					   logger.info("权重是多少啊"+wedith);
					   BigDecimal finPromaceSource = new BigDecimal(0);
					   //分子固定、
					   BigDecimal explamSource = new BigDecimal(100);
					   //总权重
					   BigDecimal allWedith = new BigDecimal(1);
					   if(memList!=null&&memList.size()!=0){
						   String tempSource = String.valueOf(memList.get(0).get("maxpreforSource"));
						   logger.info("tempSource"+tempSource);
						   if(tempSource!=null&&!(tempSource.equals("null"))){
							   //当前班级最高分
							   BigDecimal maxSource = new BigDecimal(tempSource);
							   //当前学生分数
							   String tempNowSource = String.valueOf(listExcel.get(i).get("preforSource"));
							   BigDecimal nowSource = new BigDecimal(tempNowSource);
							   //乘
							   BigDecimal mulSource = nowSource.multiply(wedith);
							   BigDecimal divSource = mulSource.multiply(explamSource);
							   boolean b = maxSource.compareTo(BigDecimal.ZERO)==0;
							   if(!b){
								   //除
								   finPromaceSource = divSource.divide(maxSource,2,BigDecimal.ROUND_HALF_UP);
							   }
						   }

						   //学生的考试成绩
						   BigDecimal examSource = new BigDecimal(String.valueOf(listExcel.get(i).get("exam")));
						   //考试成绩的权重值(减) b1.subtract(b2)
						   BigDecimal examWedith = allWedith.subtract(wedith);
						   //学生考试成绩乘以权重
						   BigDecimal finalExamSource = examSource.multiply(examWedith);
						   //学生最后的成绩
						   BigDecimal finSumSource = finPromaceSource.add(finalExamSource);
						   listExcel.get(i).put("sumSource", finSumSource);
						   listExcel.get(i).put("finPromaceSource", finPromaceSource);
						   listExcel.get(i).put("finExamSource", finalExamSource);
						   logger.info("最后的成绩是多少"+listExcel.get(i).get("sumSource"));

					   }else{
						   logger.info("次班级学生没有成绩");
					   }

				   }
				   //将平时成绩换算值和考试成绩换算值插入数据库
				   flag1 = sourceDao.updateSource(listExcel);
				   if(flag1){
					   logger.info("将平时成绩换算值和考试成绩换算值插入数据库成功");
				   }else{
					   logger.info("将平时成绩换算值和考试成绩换算值插入数据库失败");
				   }
			   }else{
				   logger.info("先将考试成绩和平时成绩插入exam表中失败");
			   }
		   }

	       returnMap.put("flag",flag1);
	       returnMap.put("msg",excelMap.get("msg"));
	       return returnMap;
	   }
	 
	 /**
	    * 查询指定目录中电子表格中所有的数据
	    * @param file 文件完整路径
	    * @return
	    */
   public  Map<String, Object> getAllByExcel(String file,String teaId){
       List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
	   Map<String, Object> returnMap = new HashMap<String, Object>();
	   List<String> arr1 = new ArrayList<String>();
	   List<String> arr2 = new ArrayList<String>();
       try {
       	//查询当前登录人（教师）所教的班级
		   Map<String, Object> classMap = new HashMap<String, Object>();
		   classMap.put("stuorteaId",teaId);
		   List<Integer> classIdList = relStuClassDao.getClassIdListByTeaId(classMap);
		   classMap.put("list",classIdList);
           Workbook rwb=Workbook.getWorkbook(new File(file));
           Sheet rs=rwb.getSheet(0);
		  //合并单元格的数量 rwb.getSheet(0).getMergedCells().length
		   logger.info("合并单元格数量"+rwb.getSheet(0).getMergedCells().length);
           int clos=rs.getColumns();//得到所有的列
           int rows=rs.getRows();//得到所有的行
		   logger.info(clos+" rows:"+rows);
           int newRow = PubMethods.getSourceNewRows(rows, rs);
           if(clos<5){
			   returnMap.put("list",null);
			   returnMap.put("msg","导入模板异常，请重新上传");
			   return  returnMap;
		   }
		   //判断模板是否正确
		   for (int j = 0; j < 6; j++){
			   arr1.add(rs.getCell(j++, 0).getContents().trim());
			   arr1.add(rs.getCell(j++, 0).getContents().trim());
			   arr1.add(rs.getCell(j++, 0).getContents().trim());
			   arr1.add(rs.getCell(j++, 0).getContents().trim());
			   arr1.add(rs.getCell(j++, 0).getContents().trim());
//			   arr1.add(rs.getCell(j++, 1).getContents().trim());

			   arr2.add("学号");
			   arr2.add("姓名");
			   arr2.add("班级");
			   arr2.add("课程");
			   arr2.add("考试成绩");
			   if(clos>5){
				   if(!rs.getCell(j++, 0).getContents().trim().equals("")){
					   arr2.add("总成绩");
					   arr1.add(rs.getCell(5, 0).getContents().trim());
				   }
			   }
		   }

		   //判断模板是否正确
		   returnMap = PubMethods.isModel(arr1,arr2,rs);
		   if(returnMap.size()!=0){
			   return returnMap;
		   }
		   if(newRow<2){
			   returnMap.put("flag", "fail");
			   returnMap.put("msg", "数据为空，导入成绩失败");
			   returnMap.put("list", null);
			   return returnMap;
		   }
		   Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
           ok:
           for (int i = 1; i < rows; i++) {
               for (int j = 0; j < 6; j++) {
            	   Map<String, Object> resultMap = new HashMap<String,Object>();
                   //第一个是列数，第二个是行数
            	   String stuorteaId=rs.getCell(j++, i).getContents().trim();
                   String userName=rs.getCell(j++, i).getContents().trim();//默认最左边编号也算一列 所以这里得j++
				   String className=rs.getCell(j++, i).getContents().trim();
				   String courseName=rs.getCell(j++, i).getContents().trim();
                   Map<String, Object> paramMap = new HashMap<String,Object>();
				   if(stuorteaId.equals("")||stuorteaId==null){
					   list = null;
					   returnMap.put("list",list);
					   returnMap.put("msg","学号不可为空");
					   break ok;
				   }
				   if((className.equals("")||className==null)){
					   list = null;
					   returnMap.put("list",list);
					   returnMap.put("msg","班级不可为空");
					   break ok;
				   }
				   if((courseName.equals("")||courseName==null)){
					   list = null;
					   returnMap.put("list",list);
					   returnMap.put("msg","课程不可为空");
					   break ok;
				   }
				   if(PubMethods.isSpecialChar(stuorteaId)||PubMethods.isSpecialChar(userName)||PubMethods.isSpecialChar(className)){
					   returnMap.put("flag", "fail");
					   returnMap.put("errMsg", "学生成绩信息不能输入特殊字符，导入成绩失败");
					   returnMap.put("list", null);
					   break ok;
				   }
				   //查询当前学生是否是当前教师所教的学生
				   classMap.put("stuorteaId",stuorteaId);
				   if(classIdList.size()==0){
					   list = null;
					   returnMap.put("list",list);
					   returnMap.put("msg","当前暂无教授信息，导入成绩失败");
					   break ok;
				   }
				   List<Map<String, Object>> stuMap = relStuClassDao.getStuByTeaIdAndClassId(classMap);
				   if(stuMap==null||stuMap.size()==0){
					   list = null;
					   returnMap.put("list",list);
					   returnMap.put("msg",stuorteaId+"学生不是您的学生，导入成绩失败");
					   break ok;
				   }

                   //通过班级名查询班级id
                   List<Map<String, Object>> classList = new ArrayList<Map<String, Object>>();
                   classList=classDao.getClassByClassName(className);
                   logger.info("班级集合"+classList);
                   int classId=0;
                   if(classList!=null&&classList.size()!=0){
                	   classId = Integer.parseInt(String.valueOf(classList.get(0).get("classId")));
                   }
				   if(classList==null||classList.size()==0){
					   list = null;
					   returnMap.put("list",list);
					   returnMap.put("msg","班级不存在，导入成绩失败");
					   break ok;
				   }
                   //通过课程名查询课程id
				   logger.info("courseName"+courseName);
                   paramMap.put("courseName", courseName);
                   Map<String, Object> courseMap = courseDao.getCourseDetailByName(paramMap);
                   logger.info("courseMap怎么空指针了"+courseMap);
                   int courseId = 0;
                   if(courseMap!=null){
                	   courseId = Integer.valueOf(String.valueOf(courseMap.get("courseId")));
                   }if(courseMap==null||courseMap.size()==0){
					   list = null;
					   returnMap.put("list",list);
					   returnMap.put("msg","课程不存在，导入成绩失败");
					   break ok;
				   }
                   if(courseMap!=null&&classList!=null&&classList.size()!=0){
                	   //平时总分 20180912将平时分去掉
//                       String preformce=rs.getCell(j++, i).getContents().trim();
					   String preformce = null;
                       if(StringUtils.isBlank(preformce)){
                    	   preformce="0";
                       }
                       BigDecimal preforSource = new BigDecimal(preformce);
                       //考试成绩
                       String exam=rs.getCell(j++, i).getContents().trim();
                       if(StringUtils.isBlank(exam)){
                    	   exam="0";
                       }


					   if (!pattern.matcher(exam).matches()) {
						   returnMap.put("list",null);
						   returnMap.put("msg","分数填写不正确，导入成绩失败");
						   break ok;
					   }
                       BigDecimal examSource = new BigDecimal(exam);
                       //总成绩
                      /* String sumSource=rs.getCell(j++, i).getContents().trim();
                       if(sumSource.equals("")||sumSource==null){
                    	   sumSource="0";
                       }*/
                       BigDecimal finsumSource = new BigDecimal(0);
//                       System.out.println("userName"+userName+" stuorteaId:"+stuorteaId+" classId:"+classId+" professionId:"+professionId+"courseId"+courseId+"preforSource"+preforSource+"examSource"+examSource);
//                       resultMap.put("userName", userName);
                       resultMap.put("classId", classId);
                       resultMap.put("stuorteaId", stuorteaId);
//                       resultMap.put("professionId", professionId);
                       resultMap.put("courseId", courseId);
                       resultMap.put("preforSource", preforSource);
                       resultMap.put("exam", exam);
                       resultMap.put("sumSource", finsumSource);
                       list.add(resultMap);
					   returnMap.put("msg","");
					   returnMap.put("list",list);
                   }else{
                	   list = null;
					   returnMap.put("list",list);
					   returnMap.put("msg","班级不存在，导入成绩失败");
                	   break ok;
                   }
                  
               }
           }
       } catch (Exception e) {
           
           e.printStackTrace();
       } 
       return returnMap;
   }
   
   /**
	 * 查询成绩设置。
	 * @throws IOException
	 */
	public Map<String, Object> getProWedith(HttpSession session,Map<String,Object> paramMap, HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			//获取当前登陆人的工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			paramMap.put("stuorteaId", stuorteaId);
			Map<String, Object> sorceMap = sourceDao.getProWedith(paramMap);
			returnMap.put("sorceMap", sorceMap);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * 获得当前登录人未结课课程列表。。
	 * @throws IOException
	 */
	public Map<String, Object> getCourseNoEndListByTeaId(HttpSession session,Map<String,Object> paramMap, HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			//获取当前登陆人的工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			paramMap.put("stuorteaId", stuorteaId);
			int pageNow=0;
			int pageSize=10;
			if(paramMap.get("pageNow")!=null&&paramMap.get("pageSize")!=null){
				pageNow =(Integer)paramMap.get("pageNow");
				pageSize = (Integer)paramMap.get("pageSize");
			}

			if(pageNow!=0){
				//获取分页数据
				int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
				paramMap.put("startNum", startNum);
			}
			returnMap.put("pageNow", pageNow);
			//20171020 查询当前登陆人所拥有的未结课的课程
			List<Map<String,Object>> courseList = sourceDao.getCourseNoEndListByTeaId(paramMap);
			returnMap.put("courseList", courseList);
			//获取全部页数
			paramMap.put("pageNow", 0);
			List<Map<String, Object>> allCourseList = sourceDao.getCourseNoEndListByTeaId(paramMap);
			int totalPage = pageUtil.getTotalPage(allCourseList, pageSize);
			returnMap.put("totalPage", totalPage);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
	
	/**
	 * 成绩设置。
	 * @throws IOException
	 */
	public Map<String,Object> addSorceSet(Map<String,Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {
		
		boolean flag = false;
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			
			//获取当前登陆人的工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request,"userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			paramMap.put("stuorteaId", stuorteaId);
			//模拟课程id
//			paramMap.put("courseId",1);
			Map<String,Object> resultMap = sourceDao.getProWedith(paramMap);
			if(resultMap!=null&&resultMap.size()!=0){
				//查询当前教师教的班级下学生是否提交过作业或实验
				List<Map<String,Object>> taskMap = courseDao.getTeaTeachTaskByTeaId(paramMap);
				if(taskMap!=null){
					if(taskMap.size()!=0&&Integer.parseInt(String.valueOf(resultMap.get("souceMark")))!=Integer.parseInt(String.valueOf(paramMap.get("souceMark")))){
						map.put("flag", false);
						map.put("errMsg", "学生已提交作业不可更改评分类型");
						return map;
					}
				}
				flag = sourceDao.updateSorceSet(paramMap);
			}else{
				flag = sourceDao.addSorceSet(paramMap);
			}
			if(flag){
				//成绩设置成功后，将未结课班级下所有学生成绩做相应更改
				//20171020号 成绩设置又改为当当前登陆人更改成绩设置的时候将当前登陆人选择的课程下未结课的班级下的学生成绩做相应更改，结课的班级学生成绩不变(给我传courseId)
				//通过教师号获取此教师所属班级
//				List<String> classList = relStuClassDao.getClassByStuorteaId(paramMap);
				List<Map<String,Object>> classList = relStuClassDao.getClassAndCourseByStuorteaId(paramMap);
				if(classList!=null&&classList.size()!=0){
					paramMap.put("classList", classList);
					//通过教师号获取此教师所属课程(未结课的)
					List<Map<String,Object>> courseList = courseDao.getTeaTeachCourseByNoEnd(paramMap);
					if(courseList!=null&&courseList.size()!=0){
						paramMap.put("courseList", courseList);
						paramMap.put("classEndMark",0);
						logger.info("paramMap"+paramMap);
						List<Map<String, Object>> memberList = sourceDao.getAllSourceList(paramMap);
						if(memberList.size()!=0){
							paramMap.put("memberList",memberList);
							//未结课的学生成绩列表
							List<Map<String, Object>> stuList = sourceDao.getNoEndCourseAllSourceList(paramMap);
							//20171020号 成绩设置又改为当当前登陆人更改成绩设置的时候将当前登陆人选择的课程下未结课的班级下的学生成绩做相应更改，结课的班级学生成绩不变(给我传courseId)
							for(int i=0;i<stuList.size();i++){
								Map<String,Object> stuMap = new HashMap<String,Object>();
								stuMap.put("stuorteaId",stuList.get(i).get("stuorteaId"));
								stuMap.put("courseId",stuList.get(i).get("courseId"));
								stuMap.put("classId",stuList.get(i).get("classId"));
								Map<String, Object> detailMap = sourceDao.getExamBySidAndCourseId(stuMap);
								//平时成绩换算值(参数是班号、课程号、学生平时分)
								BigDecimal finPromaceSource = this.proSource(stuMap, detailMap,session,request);
								//考试成绩换算值（参数考试成绩）
								BigDecimal examSource = this.examSource(stuMap, detailMap,session,request);
								//学生最后的成绩
								BigDecimal finSumSource = finPromaceSource.add(examSource);
								stuMap.put("sumSource", finSumSource);
								stuMap.put("finPromaceSource", finPromaceSource);
								stuMap.put("finExamSource", examSource);
								stuMap.put("examSource", detailMap.get("examSource"));
								//编辑成绩表，将学生总成绩、平时成绩换算值、考试成绩换算值插入数据库。
								stuMap.put("type", 1);
								stuMap.put("stuorteaId",stuList.get(i).get("stuorteaId"));
								flag = questionDao.saveQuestionByStuId(stuMap);
								if(flag){
									map.put("flag", flag);
									map.put("errMsg", "成功");
								}
							}
						}else{
							map.put("flag", true);
							map.put("errMsg", "成功");
						}
					}else{
						map.put("flag", true);
						map.put("errMsg", "成功");
					}
				}
			}else{
				map.put("flag", flag);
				map.put("errMsg", "失败");
			}




			//查询该教师下的学生是否已经有成绩
			/*List<Map<String, Object>> sourceList = sourceDao.getExamByteaId(paramMap);
			if(sourceList==null||sourceList.size()==0){
				//查询成绩设置是否已经有数据，如果有数据则做更新操作
				Map<String,Object> resultMap = sourceDao.getProWedith(paramMap);
				if(resultMap!=null){
					flag = sourceDao.updateSorceSet(paramMap);
					map.put("flag", flag);
					map.put("errMsg", "成功");
				}else{
					flag = sourceDao.addSorceSet(paramMap);
					map.put("flag", flag);
					map.put("errMsg", "成功");
				}
			}else{
				map.put("flag", flag);
				map.put("errMsg", "已有成绩不可更改权重");
			}*/
			
		} catch (Exception e) {
			throw e;
		}
		return map;
	}
	
	/*
	 * @param 学生成绩详情
	 * @throws IOException
	 */
	public Map<String, Object> getStuSourceDetail(Map<String, Object> paramMap,HttpSession session) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			
//			//查询当前要评价学生所在班级所属课程(参数是学号、课程号)
//			Map<String,Object> stuClaCouMap = relStuClassDao.getStuClaAndCou(paramMap);//这个结果里有班号
//			//查询当前班级当前课程相关学生的平时成绩(参数是班号、课程号)
//			List<Map<String,Object>> stuList = sourceDao.getStuSourceList(paramMap);
//			//将和此评价学生所在同一所班级的学生总成绩重新计算后更改数据库(参数是班号、课程号)
//			sourceDao.updateSorceBySId(paramMap);

			/*
			//平时成绩换算值(参数是班号、课程号、学生平时分)
			BigDecimal finPromaceSource = this.proSource(paramMap, detailMap,session);
			//考试成绩换算值（参数考试成绩）
			BigDecimal examSource = this.examSource(paramMap, detailMap,session);
			detailMap.put("finPromaceSource", finPromaceSource);
			detailMap.put("finExamSource", examSource);
			//学生最后的成绩
		   BigDecimal finSumSource = finPromaceSource.add(examSource);
		   paramMap.put("sumSource", finSumSource);
		   paramMap.put("examSource", examSource);
			paramMap.put("finPromaceSource", finPromaceSource);
			paramMap.put("finExamSource", examSource);
		   System.out.println("编辑成绩表，将学生总成绩插入数据库"+paramMap+"平时成绩"+finPromaceSource+"考试成绩"+examSource+"考试总成绩"+finSumSource);
			//将前台传过来的学号取出来在重新存进参数Map中获取当前学生的章节细节（因为在上步求平时成绩和考试成绩换算值时stuorteaId已经变成教师id了所以在这要重新把前台传的学号弄回来）
			String id = (String) paramMap.get("parameStuorteaId");
			paramMap.put("stuorteaId", id);
			System.out.println("最后的map"+paramMap);
			//编辑成绩表，将学生总成绩、平时成绩换算值、考试成绩换算值插入数据库。
			  paramMap.put("type", 1);
			  questionDao.saveQuestionByStuId(paramMap);
			  detailMap.put("sumSource", finSumSource);
			  System.out.println("zui="+detailMap.get("source"));
			 */
			//通过学号和课程号获取此学生成绩
			Map<String, Object> detailMap = sourceDao.getExamBySidAndCourseId(paramMap);
			returnMap.put("detailMap", detailMap);
			//通过学号和课程号获取此学生课程中每章节的分数
			List<Map<String,Object>> courseList = homeworkTestDao.getEverySourceByCourseAndSid(paramMap);
			returnMap.put("courseList", courseList);
			//查询学生姓名
			List<Map<String, Object>> stuList = memberDao.getMemberByStuorteaId(String.valueOf(paramMap.get("stuorteaId")));
			returnMap.put("userName", stuList.get(0).get("userName"));
			
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  学生成绩列表页面(学生)。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	public Map<String, Object> getStuAllSourceList(Map<String, Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			
			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			paramMap.put("stuorteaId", stuorteaId);
			//通过学生获取此学生所属课程
			List<Map<String,Object>> courseList = myCourseDao.getStuCourse(paramMap);
			returnMap.put("courseList", courseList);
			List<Map<String, Object>> memberList = sourceDao.getStuAllSourceList(paramMap);
			returnMap.put("memberList", memberList);
			returnMap.put("pageNow", pageNow);
			//获取全部页数
			paramMap.put("pageNow", 0);
			List<Map<String, Object>> allMemberList = sourceDao.getStuAllSourceList(paramMap);
			int totalPage = pageUtil.getTotalPage(allMemberList, pageSize);
			returnMap.put("totalPage", totalPage);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
	
	
	//平时成绩转换值
		public BigDecimal proSource(Map<String,Object> paramMap,Map<String,Object> detailMap,HttpSession session, HttpServletRequest request ) throws Exception{
				logger.info("查询班级最高分的参数是"+paramMap)	;
				//查询每个班级分数最高人的分数
			   List<Map<String, Object>> memList = sourceDao.getMaxPreforSource(paramMap);
			   logger.info("查询每个班级分数最高人的分数"+memList);
			   String stuorteaId = this.getId(session,paramMap,request);
			   String parameStuorteaId = (String) paramMap.get("stuorteaId");
			   paramMap.put("parameStuorteaId", parameStuorteaId);
			   paramMap.put("stuorteaId", stuorteaId);
			   logger.info("参数是"+paramMap);
			   //查询课堂权重。
			   Map<String,Object> sorceMap = sourceDao.getProWedith(paramMap);
			   logger.info("是sorceMap"+sorceMap);
			   BigDecimal wedith = (BigDecimal) sorceMap.get("classPerformance");
			   logger.info("权重是多少啊"+wedith+"参数是啥啊"+paramMap+"detailMap"+detailMap);
			   BigDecimal finPromaceSource = new BigDecimal(0);
			   //分子固定、
			   BigDecimal explamSource = new BigDecimal(100);
			   //总权重
			   BigDecimal allWedith = new BigDecimal(1);
			   if(memList!=null&&memList.size()!=0){
				  String tempSource = String.valueOf(memList.get(0).get("maxpreforSource"));
				  if(tempSource.equals("0")){
					  finPromaceSource = new BigDecimal(0);
					  return finPromaceSource;
				  }
				  logger.info("tempSource"+tempSource);
				  if(tempSource!=null&&!(tempSource.equals("null"))&&!(tempSource.equals("0"))&&!(tempSource.equals("0.00"))){
					  //当前班级最高分
					  BigDecimal maxSource = new BigDecimal(tempSource);
					  //当前学生分数
					  String tempNowSource = String.valueOf(detailMap.get("preforSource"));
					  BigDecimal nowSource = new BigDecimal(tempNowSource);
					  logger.info("maxSource"+maxSource+"explamSource"+explamSource);
					  //乘
					  BigDecimal mulSource = nowSource.multiply(wedith);
					  BigDecimal divSource = mulSource.multiply(explamSource);
					  //除
					  finPromaceSource = divSource.divide(maxSource,2,BigDecimal.ROUND_HALF_UP);
				  }
		   }
	   return finPromaceSource;
	  }
	
	//考试成绩转换值
		public BigDecimal examSource(Map<String,Object> paramMap,Map<String,Object> detailMap,HttpSession session, HttpServletRequest request ) throws Exception{
			 BigDecimal finExamSource = new BigDecimal(0);
			 	//获取当前登陆人的工号
				String stuorteaId = this.getId(session,paramMap,request);
				paramMap.put("stuorteaId", stuorteaId);
			   //查询课堂权重。
			   Map<String,Object> sorceMap = sourceDao.getProWedith(paramMap);
			   BigDecimal wedith = (BigDecimal) sorceMap.get("classPerformance");
			   logger.info("权重是多少啊"+wedith);
			   //总权重
			   BigDecimal allWedith = new BigDecimal(1);
			   //考试成绩的权重值(减) b1.subtract(b2)
 			  BigDecimal examWedith = allWedith.subtract(wedith);
			  //当前学生考试分数
			  String tempExamSource = String.valueOf(detailMap.get("examSource"));
			  BigDecimal nowSource = new BigDecimal(tempExamSource);
			  //乘
			  BigDecimal mulSource = nowSource.multiply(examWedith).setScale(2,BigDecimal.ROUND_HALF_UP);
			  finExamSource = mulSource;
	   return finExamSource;
	  }
		//判断当前登陆人是老师还是学生返回相应的学号或工号
		public String getId(HttpSession session,Map<String,Object> map, HttpServletRequest request) throws Exception{
			String stuorteaId = "";
			Map<String,Object> paramMap = new HashMap<String,Object>();
			//获取当前登录人选择的角色
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId","roleId"}, request, "userMsg");
			int roleId = Integer.parseInt(String.valueOf(sessionMap.get("roleId")));
			//获取当前登陆人的id
			String nowId =String.valueOf(sessionMap.get("stuorteaId"));
			paramMap.put("stuorteaId", nowId);
			if(roleId==1){
				logger.info("说明当前登陆人是学生，则要获取此学生所属教师工号"+roleId+"   $$$$"+nowId+"paramMap"+paramMap);
				paramMap.put("roleId", 1);
				paramMap.put("courseId", map.get("courseId"));
				//说明当前登陆人是学生，则要获取此学生所属教师工号
				Map<String,Object> relMap = relationActionImpl.getMyTeacherByCourseId(paramMap);
				stuorteaId = (String) relMap.get("stuorteaId");
			}if(roleId==2 ||roleId==5){
				logger.info("说明当前登陆人是教师，则直接从session获取当前登陆人的id"+roleId+"  %%%%"+nowId);
				//说明当前登陆人是教师，则直接从session获取当前登陆人的id
				stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			}
			logger.info("最后的id是"+stuorteaId);
			return stuorteaId;
		}
}
